package com.pj.wisdomlogistics.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.jaeger.ninegridimageview.NineGridImageView;
import com.jaeger.ninegridimageview.NineGridImageViewAdapter;
import com.pj.wisdomlogistics.MyApplication;
import com.pj.wisdomlogistics.R;
import com.pj.wisdomlogistics.cons.Cons;
import com.pj.wisdomlogistics.entity.RepairDetailInfo;
import com.pj.wisdomlogistics.entity.RepairPeopleInfo;
import com.pj.wisdomlogistics.mvp.contract.RepairDetailContract;
import com.pj.wisdomlogistics.mvp.frame.MvpActivity;
import com.pj.wisdomlogistics.mvp.frame.base.BaseView;
import com.pj.wisdomlogistics.mvp.presenter.RepairDetailPresenter;
import com.pj.wisdomlogistics.other.EventCenter;
import com.pj.wisdomlogistics.utils.ActivityManagerUtil;
import com.pj.wisdomlogistics.utils.CustomToast;
import com.pj.wisdomlogistics.utils.ShowPop;
import com.sjy.imagepicker.ImageViewerActivity;
import com.willy.ratingbar.ScaleRatingBar;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class RepairDetailActivity extends MvpActivity<RepairDetailPresenter> implements RepairDetailContract.View, ShowPop.listener {

    @BindView(R.id.ninegridview)
    NineGridImageView mNinegridview;
    @BindView(R.id.tv_repair_matter)
    TextView mTvRepairMatter;
    @BindView(R.id.tv_repair_appointment)
    TextView mTvRepairAppointment;
    @BindView(R.id.tv_repair_fault_location)
    TextView mTvRepairFaultLocation;
    @BindView(R.id.tv_repair_fault_phenomenon)
    TextView mTvRepairFaultPhoneomenon;
    @BindView(R.id.tv_repair_fault_remarks)
    TextView mTvRepairFaultRemarks;
    @BindView(R.id.tv_repair_people)
    TextView mTvRepairPeople;
    @BindView(R.id.bt_orders)
    Button mBtOrders;
    @BindView(R.id.ratingBar)
    ScaleRatingBar mSRatingBar;
    @BindView(R.id.ll_pj)
    LinearLayout mLayoutPj;
    @BindView(R.id.tv_access)
    TextView mTvAccess;
    @BindView(R.id.ng_complete)
    NineGridImageView mNgComplete;
    @BindView(R.id.tv_remark_complete)
    TextView mTvRemarkComplete;
    @BindView(R.id.rel_basic_info)
    RelativeLayout mRelBasicInfo;
    @BindView(R.id.rel_line1)
    RelativeLayout mRelLine1;
    @BindView(R.id.ll_complete)
    LinearLayout mLlComplete;
    @BindView(R.id.rel_line2)
    RelativeLayout mRelLine2;
    @BindView(R.id.tv_repair_place)
    TextView mTvPlace;

    private int repairId = -1;
    private int repairTransactId = -1;
    private int repairApplyId = -1;
    private int state = -1;

    private boolean isRepairPorition = false;


    @Override
    public void onError(String errorMsg) {
        dismissProgressDialog();
        CustomToast.showToast(this, errorMsg, 1000);
    }

    @Override
    public void onSuccess(final RepairDetailInfo mInfo) {
        dismissProgressDialog();

        EventBus.getDefault().post(new EventCenter<>(Cons.Other.MY_TRANSACT));

        repairApplyId = mInfo.getRepairApplyReturn().getRepairApplyID();
        state = mInfo.getRepairApplyReturn().getState();

        if (mInfo.getPicList() == null || mInfo.getPicList().size() == 0) {
            mRelBasicInfo.setVisibility(View.GONE);
            mRelLine1.setVisibility(View.GONE);
            mNinegridview.setAdapter(null);
        } else {
            mRelBasicInfo.setVisibility(View.VISIBLE);
            mRelLine1.setVisibility(View.VISIBLE);
            for (int i = 0; i < mInfo.getPicList().size(); i++) {
                mInfo.getPicList().set(i, mInfo.getHomePicPath() + mInfo.getPicList().get(i));
            }
            mNinegridview.setAdapter(mAdapter);
            mNinegridview.setImagesData(mInfo.getPicList());
        }

        if (mInfo.getFinishPicList() == null || mInfo.getFinishPicList().size() == 0) {
            mLlComplete.setVisibility(View.GONE);
            mRelLine2.setVisibility(View.GONE);
            mNgComplete.setAdapter(null);
        } else {
            mLlComplete.setVisibility(View.VISIBLE);
            mRelLine2.setVisibility(View.VISIBLE);
            for (int i = 0; i < mInfo.getFinishPicList().size(); i++) {
                mInfo.getFinishPicList().set(i, mInfo.getHomePicPath() + mInfo.getFinishPicList().get(i));
            }
            mNgComplete.setAdapter(mAdapter);
            mNgComplete.setImagesData(mInfo.getFinishPicList());

            mTvRemarkComplete.setText("完成说明：" +
                    (TextUtils.isEmpty(mInfo.getRepairApplyReturn().getFixWorkerRemark()) ? "无" : mInfo.getRepairApplyReturn().getFixWorkerRemark()));
        }


        String questions = "";
        for (int i = 0; i < mInfo.getRepairApplyReturn().getQuestionList().size(); i++) {
            questions += mInfo.getRepairApplyReturn().getQuestionList().get(i) + ",";
        }
        questions = questions.substring(0, questions.length() - 1);
        mTvRepairMatter.setText(String.format(getResources().getString(R.string.apply_detail_repair_matter, questions)));
        if (TextUtils.isEmpty(mInfo.getRepairApplyReturn().getBespeakStartTime()) || mInfo.getRepairApplyReturn().getBespeakStartTime() == null) {
            mTvRepairAppointment.setText(String.format(getResources().getString(R.string.apply_detail_repair_appointment, "无")));
        } else {
            mTvRepairAppointment.setText(String.format(getResources().getString(R.string.apply_detail_repair_appointment,
                    mInfo.getRepairApplyReturn().getBespeakStartTime() + " - " + mInfo.getRepairApplyReturn().getBespeakEndTime())));
        }
        mTvRepairFaultLocation.setText(String.format(getResources().getString(R.string.apply_detail_repair_fault_location,
                mInfo.getRepairApplyReturn().getFaultPlace())));
        mTvRepairFaultPhoneomenon.setText(String.format(getResources().getString(R.string.apply_detail_repair_fault_phenomenon,
                mInfo.getRepairApplyReturn().getFaultDetail())));
        mTvRepairFaultRemarks.setText(String.format(getResources().getString(R.string.apply_detail_repair_fault_remarks,
                TextUtils.isEmpty(mInfo.getRepairApplyReturn().getRemark()) ? "无" : mInfo.getRepairApplyReturn().getRemark())));
        if(mInfo.getRepairApplyReturn().getPlace() == null){
            mTvPlace.setText("会议地点：无");
        }else{
            mTvPlace.setText("维修地点：" + (mInfo.getRepairApplyReturn().getPlace().equals("1") ? "政府大楼" : mInfo.getRepairApplyReturn().getPlace().equals("2") ? "双和园" : "暂无"));
        }

        if (mInfo.getRepairApplyReturn().getState() > 0) {
            mTvRepairPeople.setVisibility(View.VISIBLE);
            mTvRepairPeople.setText(String.format(getResources().getString(R.string.apply_detail_repair_people,
                    mInfo.getRepairApplyReturn().getFixWorkerName() + "   " + mInfo.getRepairApplyReturn().getFixWorkerTel())));
        }

        if (mInfo.getRepairApplyReturn().getState() == 0 && repairTransactId != -1 && !MyApplication.isGzh) {
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                if (MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.PORITION_REPAIR)) {
                    mBtOrders.setVisibility(View.VISIBLE);
                    mBtOrders.setText("分配");
                    isRepairPorition = true;
                } else if (MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.ORDER_REPAIR)) {
                    mBtOrders.setVisibility(View.VISIBLE);
                    mBtOrders.setText("接单");
                    isRepairPorition = false;
                }
            }
        }

        if (mInfo.getRepairApplyReturn().getState() == 1 && repairApplyId != -1 && !MyApplication.isGzh) {
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                if (MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.ORDER_REPAIR)) {
                    mBtOrders.setVisibility(View.VISIBLE);
                    mBtOrders.setText("完成");
                    isRepairPorition = true;
                }
            }

            mBtOrders.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent mIntent = new Intent(RepairDetailActivity.this, RepairFinishActivity.class);
                    mIntent.putExtra(Cons.RepairInfo.REPAIR_ID, repairApplyId);
                    startActivity(mIntent);
                }
            });
        }


        //待评价
        if (mInfo.getRepairApplyReturn().getState() == 2 && MyApplication.userID.equals(mInfo.getRepairApplyReturn().getUserID())) {
            mBtOrders.setVisibility(View.VISIBLE);
            mBtOrders.setText("评价");
            mBtOrders.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ShowPop.showTurnDown(RepairDetailActivity.this, 101, mBtOrders);
                }
            });
        }

        //已评价
        if (mInfo.getRepairApplyReturn().getState() == 3) {
            mSRatingBar.setVisibility(View.VISIBLE);
            mSRatingBar.setRating(mInfo.getRepairApplyReturn().getLevels());
            mLayoutPj.setVisibility(View.VISIBLE);
            mTvAccess.setText(TextUtils.isEmpty(mInfo.getRepairApplyReturn().getAssess()) ? "无" : mInfo.getRepairApplyReturn().getAssess());
            mSRatingBar.setTouchable(false);
        }

    }

    @Override
    public void onOrderSuccess() {
        successToast("接单成功");
    }

    @Override
    public void onPoritionSuccess() {
        successToast("分配成功");
    }

    @Override
    public void onPjSuccess() {
        dismissProgressDialog();
        CustomToast.showToast(this, "评价成功", 1000);
        EventBus.getDefault().post(new EventCenter<>(Cons.Other.MY_APPLY));
        ActivityManagerUtil.create().finishActivity();
    }


    public void successToast(String toast) {
        dismissProgressDialog();
        CustomToast.showToast(this, toast, 1000);
        EventBus.getDefault().post(new EventCenter<>(Cons.Other.MY_TRANSACT));
        ActivityManagerUtil.create().finishActivity();
    }

    @Override
    protected BaseView getBaseView() {
        return this;
    }

    @Override
    public void initView() {
        repairId = getIntent().getIntExtra(Cons.RepairInfo.REPAIR_ID, -1);
        repairTransactId = getIntent().getIntExtra(Cons.RepairInfo.REPAIR_RANSACT_ID, -1);

        mPresenter.findRepairDetail(repairId != -1 ? repairId : repairTransactId);
        showProgressDialog();

        ShowPop.setListner(this);
    }

    @Override
    public void initData() {

    }

    @Override
    public int getContentView() {
        return R.layout.activity_repair_detail;
    }

    @Override
    public boolean isApplyEventBus() {
        return true;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {
        if (eventCenter.getEventCode() == Cons.RepairInfo.REPAIR_PORITION_OK) {
            RepairPeopleInfo mInfo = (RepairPeopleInfo) eventCenter.getData();
            mPresenter.repairAllot(
                    MyApplication.userID,
                    mInfo.getFixWorkerId(),
                    mInfo.getFixWorkerName(),
                    mInfo.getFixWorkerTel(),
                    repairApplyId + "",
                    "",
                    state + ""
            );
            showProgressDialog();
        } else if (eventCenter.getEventCode() == Cons.RepairInfo.REPAIR_FINISH_OK) {
            mPresenter.findRepairDetail(repairId != -1 ? repairId : repairTransactId);
            showProgressDialog();
        }
        mBtOrders.setVisibility(View.GONE);
    }


    @OnClick({R.id.iv_back, R.id.bt_orders})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                ActivityManagerUtil.create().finishActivity();
                break;
            case R.id.bt_orders:
                if (!isRepairPorition) {
                    mPresenter.orderRepair(
                            MyApplication.userID,
                            repairTransactId);
                } else {
                    startActivity(RepairPoritionActivity.class);
                }
                showProgressDialog();
                break;
        }
    }

    private NineGridImageViewAdapter<String> mAdapter = new NineGridImageViewAdapter<String>() {
        @Override
        protected void onDisplayImage(Context context, ImageView imageView, String s) {
            RequestOptions options = new RequestOptions()
                    .centerCrop()
                    .priority(Priority.HIGH);
            Glide.with(context).load(s).apply(options).into(imageView);
        }

        @Override
        protected ImageView generateImageView(Context context) {
            return super.generateImageView(context);
        }

        @Override
        protected void onItemImageClick(Context context, ImageView imageView, int index, List<String> list) {
            Intent intent = new Intent(RepairDetailActivity.this, ImageViewerActivity.class);
            intent.putExtra(ImageViewerActivity.CURRENT_POS, index);
            intent.putStringArrayListExtra(ImageViewerActivity.IMAGE_PATH_LIST, (ArrayList<String>) list);
            startActivity(intent);
        }

    };

    @Override
    public void showTurnDown(int state, String text, int rating) {
        if (state == 101) {
            mPresenter.assessRepair(
                    text,
                    repairApplyId + "",
                    rating
            );
        }
        showProgressDialog();
    }
}
